package com.example.shengyin.controller;

import com.example.shengyin.util.Result;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.net.BindException;

@RestControllerAdvice
public class ErrorConfigration {
    @ExceptionHandler(ConstraintViolationException.class)
    public Result hanle(ConstraintViolationException e)
    {
        StringBuilder b=new StringBuilder();
        for (ConstraintViolation f:e.getConstraintViolations())
            b.append(f.getMessage()+"\n");
        return Result.error(b.toString());
    }

    @ExceptionHandler(BindException.class)
    public Result handle(org.springframework.validation.BindException e)
    {
        StringBuilder b=new StringBuilder();
        for (ObjectError f:e.getAllErrors())
            b.append(f.getDefaultMessage()+"\n");
        return Result.error(b.toString());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handle(MethodArgumentNotValidException e)
    {
        StringBuilder b=new StringBuilder();
        for (ObjectError f:e.getBindingResult().getAllErrors())
            b.append(f.getDefaultMessage()+"\n");
        return Result.error(b.toString());
    }
}
